#!/usr/bin/python3
from datetime import datetime
from datetime import timedelta
import pymysql
import sys
from util import datetime_to_string
from tushare_api import fetch_data_pro_bar

import tushare

print(tushare.__version__)

# C:\Users\zhu.chunfeng\Anaconda3\python.exe C:/Users/zhu.chunfeng/Desktop/finance/tushare/tushare_main.py
# 1.2.62

# ('000016.SH', '上证50')
# ('399673.SZ', '创业板50')
# ('399300.SZ', '沪深300')
# ('000688.SH', '科创50')

# ['399975','399967','980017','931151','399976','990001','000815','931079']
# 399975 证券公司 399967 中证军工 980017 国证芯片指数 931151光伏产业指数 399976CS新能车指数 990001中华半导体人民币指数 000815细分食品指数 931079 5G通信指数
# ['931151','990001','931079']

# 打开数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="root", database="gupiao")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# cursor.execute("select ts_code from ts_code")
# print(cursor.rowcount)
# fetchall = cursor.fetchall()
# print(fetchall.__len__())
# for ts_code_tuple in fetchall:
#     tsCode = ts_code_tuple[0][0:6]

# for tsCode in ["000905"]:
#     print(tsCode)
#
# sys.exit(0)
#
# for tsCode in ['000688', '000905', '399673', '000016', '399300']:
for tsCode in ['399986']:
    # tsCode = '000004'
    basic = 'index'
    freq = "5min"
    fromTime = datetime(2010, 1, 1)
    ##### 查询全称
    sql = ''
    if basic == 'stock':
        sql = "select ts_code,name from stock_basic where ts_code like '" + tsCode + "%'"
    elif basic == 'index':
        sql = "select ts_code,name from index_basic where ts_code like '" + tsCode + "%'"
    elif basic == 'fund':
        sql = "select ts_code,name from fund_basic where ts_code like '" + tsCode + "%'"
    elif basic == 'cb':
        sql = "select ts_code,name from stock_basic where ts_code like '" + tsCode + "%'"
    else:
        raise Exception('basic 枚举有误!')
    print(sql)

    ##### 获取tsCode
    cursor.execute(sql)
    if cursor.rowcount == 0:
        raise Exception("没有相关的股票代码" + tsCode)
    if cursor.rowcount > 1:
        raise Exception("查询到多个股票代码" + cursor.fetchall())
    fetchone = cursor.fetchone()
    print(fetchone)
    tsCode = fetchone[0]


    ##### 获取最早的交易时间
    if basic == 'stock':
        sql = "select trade_time from pro_bar_stock  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    elif basic == 'index':
        sql = "select trade_time from pro_bar_index  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    elif basic == 'fund':
        sql = "select trade_time from pro_bar_fund  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    elif basic == 'cb':
        sql = "select trade_time from pro_bar_cb  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    else:
        raise Exception('basic 枚举有误!')
    print(sql)
    cursor.execute(sql)
    print(cursor.rowcount)

    earlyTime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)
    if cursor.rowcount > 0:
        earlyTime = cursor.fetchone()[0]  # 2016-01-04 09:30:00
        earlyTime = datetime(earlyTime.year, earlyTime.month, earlyTime.day)
    print(earlyTime)

    #从 fromTime 到 earlyTime
    if fromTime < earlyTime:
        while fromTime < earlyTime:
            timeDiff = timedelta(days=40)
            timePre = earlyTime - timeDiff
            if fromTime <= timePre:
                print(datetime_to_string(timePre) + '--->' + datetime_to_string(earlyTime))
                fetch_data_pro_bar(tsCode, datetime_to_string(timePre), datetime_to_string(earlyTime), basic, freq)
                earlyTime = timePre
            else:
                timePre = fromTime
                print(datetime_to_string(timePre) + '----->' + datetime_to_string(earlyTime))
                fetch_data_pro_bar(tsCode, datetime_to_string(timePre), datetime_to_string(earlyTime), basic, freq)
                earlyTime = timePre

    ##### 获取最晚的交易时间
    if basic == 'stock':
        sql = "select trade_time from pro_bar_stock  where ts_code ='" + tsCode + "' order by trade_time desc limit 1"
    elif basic == 'index':
        sql = "select trade_time from pro_bar_index  where ts_code ='" + tsCode + "' order by trade_time desc limit 1"
    elif basic == 'fund':
        sql = "select trade_time from pro_bar_fund  where ts_code ='" + tsCode + "' order by trade_time desc limit 1"
    elif basic == 'cb':
        sql = "select trade_time from pro_bar_cb  where ts_code ='" + tsCode + "' order by trade_time desc limit 1"
    else:
        raise Exception('basic 枚举有误!')
    print(sql)
    cursor.execute(sql)
    print(cursor.rowcount)

    # lateTime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)
    if cursor.rowcount > 0:
        lateTime = cursor.fetchone()[0]  # 2016-01-04 09:30:00
        lateTime = datetime(lateTime.year, lateTime.month, lateTime.day)
        lateTime = lateTime + timedelta(days=1)

        todayTime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)
        #从 lateTime 到 现在
        while lateTime < todayTime:
            timeDiff = timedelta(days=40)
            timeNext = lateTime + timeDiff
            if timeNext > todayTime:
                #从 lateTime 到 timeNext
                timeNext = todayTime
                print(datetime_to_string(lateTime) + '--->' + datetime_to_string(timeNext))
                fetch_data_pro_bar(tsCode, datetime_to_string(lateTime), datetime_to_string(timeNext), basic, freq)
                lateTime = timeNext
            else:
                print(datetime_to_string(lateTime) + '--->' + datetime_to_string(timeNext))
                fetch_data_pro_bar(tsCode, datetime_to_string(lateTime), datetime_to_string(timeNext), basic, freq)
                lateTime = timeNext


# 关闭数据库连接
db.close()
